package com.whf.service.impl;

import com.whf.converter.OrderMaster2OrderDTO;
import com.whf.dataobject.OrderDetail;
import com.whf.dataobject.OrderMaster;
import com.whf.dataobject.ProductInfo;
import com.whf.dto.CartDTO;
import com.whf.dto.OrderDTO;
import com.whf.enums.OrdersStatusEnum;
import com.whf.enums.PayStatusEnum;
import com.whf.enums.ResultEnum;
import com.whf.exception.SellException;
import com.whf.repository.OrderDetailRepository;
import com.whf.repository.OrderMasterRepository;
import com.whf.service.OrderService;
import com.whf.service.ProductService;
import com.whf.utils.KeyUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Created by Administrator on 2018/7/13 0013.
 */
@Service
@Slf4j
public class OrderServiceImpl implements OrderService {

    @Autowired
    private ProductService productService;
    @Autowired
    private OrderDetailRepository orderDetailRepository;
    @Autowired
    private OrderMasterRepository orderMasterRepository;

    //创建订单
    @Override
    //添加事务
    @Transactional
    public OrderDTO create(OrderDTO orderDTO) {
        //生成订单号
        String orderId = KeyUtil.uniqueKey();
        //定义一个总价,初始化为0
        BigDecimal orderAmount = new BigDecimal(BigInteger.ONE);
        //订单中的单价需要从商品表格中查询
        for (OrderDetail orderDetail : orderDTO.getOrderDetailList()) {
            ProductInfo productInfo = productService.findOneByProductId(orderDetail.getProductId());
            if (productInfo == null) {
                //商品不存在
                throw new SellException(ResultEnum.PRODUCT_NOT_EXIST);
            }
            //计算总价,bigdecimal计算时需要使用方法计算,不可以直接使用+-*/
            orderAmount = orderAmount.add(productInfo.getProductPrice().multiply(new BigDecimal(orderDetail.getProductQuantity())));

            //每个详情入库
            //使用beanutils工具将productInfo中的属性值cope到orderDetail
            BeanUtils.copyProperties(productInfo, orderDetail);
            //设置订单详情id
            orderDetail.setDetailId(KeyUtil.uniqueKey());
            //设置订单id
            orderDetail.setOrderId(orderId);
            //写入数据库
            orderDetailRepository.save(orderDetail);
        }
        //将orderMaster写入数据库
        OrderMaster orderMaster = new OrderMaster();
        //设置订单号
        orderDTO.setOrderId(orderId);
        BeanUtils.copyProperties(orderDTO, orderMaster);
        orderMaster.setOrderAmount(orderAmount);
        orderMaster.setOrderStatus(OrdersStatusEnum.NEW.getCode());
        orderMaster.setPayStatus(PayStatusEnum.WAIT.getCode());
        //写入数据库
        orderMasterRepository.save(orderMaster);
        //扣库存
        List<CartDTO> cartDTOList = new ArrayList<>();
        //通过lumbda表达式直接获取
        cartDTOList = orderDTO.getOrderDetailList().stream().map(e ->
                new CartDTO(e.getProductId(), e.getProductQuantity())
        ).collect(Collectors.toList());
        productService.decreaseStock(cartDTOList);
        return orderDTO;
    }

    //查询一个订单
    @Override
    public OrderDTO findOne(String orderId) {
        //根据orderid查询订单master
        OrderMaster orderMaster = orderMasterRepository.findById(orderId).get();
        if(orderMaster==null){
            throw new SellException(ResultEnum.ORDER_NOT_EXIST);
        }
        List<OrderDetail> orderDetailList = orderDetailRepository.findByOrderId(orderId);
        if(CollectionUtils.isEmpty(orderDetailList)){
            throw new SellException(ResultEnum.ORDER_NOT_DETAIL);
        }
        OrderDTO orderDTO=new OrderDTO();
        BeanUtils.copyProperties(orderMaster,orderDTO);
        orderDTO.setOrderDetailList(orderDetailList);

        return orderDTO;
    }

    //返回某个用户的订单列表,无需订单中的商品详情
    @Override
    public Page<OrderDTO> findAll(String buyerOpenId,Pageable pageable) {
        Page<OrderMaster> orderMasterPage = orderMasterRepository.findByBuyerOpenid(buyerOpenId, pageable);
        List<OrderMaster> content = orderMasterPage.getContent();
        List<OrderDTO> orderDTOList = OrderMaster2OrderDTO.convert(content);
        //将list集合转成page
        Page<OrderDTO> orderDTOPage=new PageImpl<OrderDTO>(orderDTOList,pageable,orderMasterPage.getTotalElements());

        return orderDTOPage;
    }

    //取消订单
    @Override
    @Transactional
    public OrderDTO cancel(OrderDTO orderDTO) {
        //判断订单状态
        Integer orderStatus = orderDTO.getOrderStatus();
        if(orderStatus!=OrdersStatusEnum.NEW.getCode()){
            log.error("[取消订单]订单状态不正确,orderId={},orderStatus={}",orderDTO.getOrderId(),orderDTO.getOrderStatus());
            throw new SellException(ResultEnum.ORDER_ERROR_STATUS);
        }
        OrderMaster orderMaster1=new OrderMaster();
        orderDTO.setOrderStatus(OrdersStatusEnum.CANCEL.getCode());
        BeanUtils.copyProperties(orderDTO,orderMaster1);
        //修改订单状态
        OrderMaster save = orderMasterRepository.save(orderMaster1);
        if(save==null){
            log.error("[取消订单]订单更新失败,orderId={},orderStatus={}",orderDTO.getOrderId(),orderDTO.getOrderStatus());
            throw new SellException(ResultEnum.ORDER_FAIL_UPDATE);
        }
        //返回库存
        if(CollectionUtils.isEmpty(orderDTO.getOrderDetailList())){
            log.error("[取消订单]该订单无商品,orderDTO={}",orderDTO);
            throw new SellException(ResultEnum.ORDER_DETAIL_EMPTY);
        }
        //添加库存
        List<CartDTO> cartDTOList=orderDTO.getOrderDetailList().stream()
                .map(e->new CartDTO(e.getProductId(),e.getProductQuantity()))
                .collect(Collectors.toList());
        productService.increaseStock(cartDTOList);

        //判断是否已支付
        if(orderMaster1.getPayStatus().equals(PayStatusEnum.SUCCESS)){
            //TODO
        }
        return orderDTO;
    }

    //完结订单
    @Override
    public OrderDTO finish(OrderDTO orderDTO) {
        //判断订单状态
        OrderMaster orderMaster = orderMasterRepository.findById(orderDTO.getOrderId()).get();
        Integer orderStatus = orderMaster.getOrderStatus();
        if(orderStatus!=OrdersStatusEnum.NEW.getCode()){
            log.error("[完结订单]订单状态不正确,orderId={},orderStatus={}",orderDTO.getOrderId(),orderDTO.getOrderStatus());
            throw new SellException(ResultEnum.ORDER_ERROR_STATUS);
        }
        //修改订单状态
        orderMaster.setOrderStatus(OrdersStatusEnum.FINISHED.getCode());
        orderDTO.setOrderStatus(OrdersStatusEnum.FINISHED.getCode());
        OrderMaster save = orderMasterRepository.save(orderMaster);
        if(save==null){
            log.error("[完结订单]更新失败,orderMaster={}" ,orderMaster);
            throw new SellException(ResultEnum.ORDER_FAIL_UPDATE);
        }

        return orderDTO;
    }

    @Override
    public OrderDTO paid(OrderDTO orderDTO) {
        //判断订单状态
        OrderMaster orderMaster = orderMasterRepository.findById(orderDTO.getOrderId()).get();
        Integer orderStatus = orderMaster.getOrderStatus();
        if(orderStatus!=OrdersStatusEnum.NEW.getCode()){
            log.error("[支付订单]订单状态不正确,orderId={},orderStatus={}",orderDTO.getOrderId(),orderDTO.getOrderStatus());
            throw new SellException(ResultEnum.ORDER_ERROR_STATUS);
        }
        //判断支付状态
        if (!orderMaster.getPayStatus().equals(PayStatusEnum.WAIT.getCode())){
            log.error("[支付订单]订单状态不正确,orderId={},payStatus={}",orderMaster.getOrderId(),orderMaster.getPayStatus());
            throw new SellException(ResultEnum.PAY_FAIL_STATUS);
        }
        //修改支付状态
        orderMaster.setPayStatus(PayStatusEnum.SUCCESS.getCode());
        orderDTO.setPayStatus(PayStatusEnum.SUCCESS.getCode());
orderMasterRepository.save(orderMaster);
        return orderDTO;
    }

    @Override
    public Page<OrderDTO> findAllList(Pageable pageable) {
        Page<OrderMaster> comment = orderMasterRepository.findAll(pageable);
        List<OrderDTO> orderDTOList = OrderMaster2OrderDTO.convert(comment.getContent());
        //将list集合转成page
        Page<OrderDTO> orderDTOPage=new PageImpl<OrderDTO>(orderDTOList,pageable,comment.getTotalElements());

        return orderDTOPage;
    }
}
